/**
 * Electron主进程
 */
import {
    app,
    BrowserWindow,
    dialog,
    Menu,
    nativeTheme
} from "electron";
import path from "path";
import { electronLogger } from "../logger/logger";

/**
 * 主窗口
 */
let mainWindow: BrowserWindow | null = null

/**
 * 是否为开发环境
 */
const isDev: boolean = process.env.NODE_ENV == 'development'

/**
 * 应用地址
 */
const appUrl: string = "http://localhost:5173"

/**
 * 应用名称
 */
const appName: string = "文渊阁问 - openKylin FAQ平台"

/**
 * 分辨率
 */
const windowsReslolution: { width: number, height: number } = {
    width: 960,
    height: 600
}

/**
 * 日志
 */
const logger = electronLogger;

/**
 * 创建主窗口
 */
function createWindow(): void {
    // 删除菜单栏
    Menu.setApplicationMenu(null);
    mainWindow = new BrowserWindow({
        title: `${appName}`,
        width: windowsReslolution.width,
        height: windowsReslolution.height,
        minHeight: windowsReslolution.height,
        minWidth: windowsReslolution.width,
        webPreferences: {
            // require和contextBridge导致的contextIsolation问题
            contextIsolation: false,
            devTools: true,
            nodeIntegration: true,
            preload: path.join(__dirname, "./preload.js")
        },
    })

    // 强制使用浅色主题
    nativeTheme.themeSource = 'light';

    mainWindow.on(`ready-to-show`, () => {
        logger.info("主窗口已准备就绪");
    })

    if (!isDev) {
        logger.info("生产环境");
        const indexPath = path.resolve(__dirname, "../dist-electron/index.html")
        console.log(indexPath)
        mainWindow.loadFile(indexPath)
        mainWindow.on("closed", () => {
            mainWindow = null
        })

    }
    else {
        logger.info("开发环境");
        let appdevtools: BrowserWindow | null = new BrowserWindow({
            title: `${appName} - DevTool`,
            width: windowsReslolution.width,
            height: windowsReslolution.height,
            backgroundColor: "#2e2c29"
        });
        appdevtools.on("closed", () => {
            appdevtools = null
        });
        mainWindow.loadURL(appUrl);
        mainWindow.webContents.setDevToolsWebContents(appdevtools.webContents)
        mainWindow.webContents.openDevTools({ mode: 'detach' })
        appdevtools.setPosition(mainWindow.getPosition()[0] + mainWindow.getSize()[0] / 2, mainWindow.getPosition()[1] + mainWindow.getSize()[1] / 2)
        mainWindow.on("closed", () => {
            if (appdevtools) {
                appdevtools.close()
            }
            mainWindow = null
        })
    }

    // 监听窗口关闭事件
    mainWindow.on("close", (event: Electron.Event) => {
        if (!mainWindow) return
        const choice = dialog.showMessageBoxSync(mainWindow, {
            type: "question",
            buttons: ["确认", "取消"],
            title: "是否退出",
            message: `是否退出 ${appName}`
        });
        if (choice === 0) {
            mainWindow.destroy()
            app.quit()
        }
        else if (choice === 1) {
            event.preventDefault()
        }

    });

}

import "./ipcMainHandlers";


app.whenReady().then(() => {
    logger.info("App is ready");
    createWindow();
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    })
})


app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
})

// quit之前
app.on(`before-quit`, () => {
    logger.info("App quit");
})





